package com.yuntsg.nnsfcp.util.zhang;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

public class HttpUtilHttps {
    public static String getHtml(CookieStore cookieStore, String url, String referer) {
        System.out.println("httpclient里面的地址" + url);
        String html = "";
        SSLContext sslcontext = null;
        try {
            sslcontext = createIgnoreVerifySSL();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

//    CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setConnectionManager(connManager)
                    .setDefaultCookieStore(cookieStore)
//              .setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httpget = new HttpGet(url);
                RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);
                httpget.setConfig(requestConfig);
                httpget.addHeader(HttpHeaders.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
                httpget.addHeader(HttpHeaders.REFERER, referer);
                responce = httpClient.execute(httpget);// 得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();// 返回码
                System.out.println("状态码" + resStatu);
                System.out.println("httpclient耗时"
                        + (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static String postHtml(CookieStore cookieStore, String url, String referer, String args) {
        System.out.println("httpclient里面的地址" + url);
        String html = "";
//    CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {

            CloseableHttpClient httpClient = HttpClients.custom()
                    .setDefaultCookieStore(cookieStore)
//              .setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpPost httppost = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            try {
                httppost = new HttpPost(url);
                RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);
                httppost.setConfig(requestConfig);
                httppost.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
                httppost.addHeader(HttpHeaders.USER_AGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
                httppost.addHeader(HttpHeaders.REFERER, referer);
                httppost.setEntity(new StringEntity(args));
                responce = httpClient.execute(httppost);// 得到responce对象
                int resStatu = responce.getStatusLine().getStatusCode();// 返回码
                System.out.println("状态码" + resStatu);
                System.out.println("httpclient耗时"
                        + (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {// 200正常 其他就不对
                    HttpEntity entity = responce.getEntity(); // 获得相应实体
                    if (entity != null) {
                        html = EntityUtils.toString(entity, "UTF-8").replace(
                                "&nbsp;", " ");
                        if (!html.contains("请输入以下验证码")) {
                            break;
                        } else {
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return html;
    }

    public static Boolean DownPdfWithProxy(CookieStore cookieStore, String url, String referer, String filename) {
        Boolean result = false;

        System.out.println("httpclient里面的地址" + url);
//    CredentialsProvider credsProvider = LoadInfo.build();

        for (int i = 1; i <= 3; i++) {
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore)
//              .setDefaultCredentialsProvider(credsProvider)
                    .build();
            HttpGet httpget = null;
            long time1 = System.currentTimeMillis();
            CloseableHttpResponse responce;
            int resStatu = 0;
            try {
                while (true) {

                    httpget = new HttpGet(url);
                    RequestConfig requestConfig = LoadInfo.buildRequestConfigureWithProxy(true);

                    httpget.setConfig(requestConfig);
                    httpget.addHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36");
                    httpget.addHeader(HttpHeaders.REFERER, referer);
                    responce = httpClient.execute(httpget);//得到responce对象

                    resStatu = responce.getStatusLine().getStatusCode();//返回码

                    if (resStatu != 301 && resStatu != 302) {
                        break;
                    }
                    url = responce.getHeaders("Location")[0].getValue().replace(" ", "");
                    System.out.println(url);
                }


                System.out.println("状态码" + resStatu);
                System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1));
                if (resStatu == HttpStatus.SC_OK) {//200正常  其他就不对
                    HttpEntity entity = responce.getEntity();   //获得相应实体
                    if (entity != null) {
                        byte[] buffer = EntityUtils.toByteArray(entity);
                        try {
                            File file = new File(filename);
                            File path = new File(file.getParent());
                            if (!path.exists()) {
                                path.mkdirs();
                            }
                            createFile(filename, buffer);
                            result = true;
                            break;
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("查看异常的字符串" + e.toString());
                if (e.toString().contains("java.net.UnknownHostException")) {

                }
                if (e.toString().contains("connect time out")) {

                }
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return result;
    }

    public static void createFile(String path, byte[] content)
            throws IOException {

        FileOutputStream fos = new FileOutputStream(path);
        fos.write(content);
        fos.close();
    }


    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }
}
